What is the use of the yield keyword in C#?
What is the use of the yield keyword in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
13-Jul-2023The
yield
keyword in C# is used to create iterators. An iterator is a method that can be used to iterate over a collection of data. Theyield
keyword allows you to create iterators that can be used to iterate over collections that are not fully loaded into memory.For example, the following code shows how to create an iterator that can be used to iterate over a list of numbers:
C#
This code creates a method called
GetNumbers()
that returns an iterator. TheGetNumbers()
method uses theyield
keyword to return the next number in the list. Theyield
keyword also allows theGetNumbers()
method to continue iterating even if the list of numbers is not fully loaded into memory.The
yield
keyword can be used to create iterators for a variety of different collections, including lists, arrays, and sets. Theyield
keyword can also be used to create iterators for custom collections.